package com.util.gen;

import com.util.RandomUtil;
import com.util.TaskUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ImageGenUtil {

    private static final String BG_IMG_PATH = ImageGenUtil.class.getResource("/static/bg1.jpg").getPath();
    private static final String IMG_FORMAT = "png";
    private static final AtomicInteger IMAGE_INDEX = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        TaskUtil.runMultiTasks(1000, "/Volumes/APFS/Downloads/batch/raws", ImageGenUtil::genImage);
//        TaskUtil.runMultiTasks(1000, "D:\\cpz\\imgs", ImageGenUtil::genImage);
//        System.err.println(getImage(2000, 1000));
    }

    public static String getImage(int width, int height) throws Exception {
        String rootPath = new ClassPathResource("").getPath();
        String filePath = rootPath + File.separator + System.currentTimeMillis() + "." + IMG_FORMAT;
        genImage(width, height, filePath);
        return filePath;
    }

    public static void genImage(String dirPath) {
        int index = IMAGE_INDEX.addAndGet(1);
        try {
            int x = RandomUtil.getRoundRandomInt(100, 2160);
            int y = RandomUtil.getRoundRandomInt(100, 1600);
            genImage(x, y, dirPath + File.separator + index + "." + IMG_FORMAT);
            log.info("生成第{}张图片成功\n", index);
        } catch (Exception e) {
            log.error("生成第{}张图片失败: {}\n", index, e.getMessage(), e);
        }
    }

    public static void genImage(int width, int height, String filePath) throws Exception {
        BufferedImage bgImg = ImageIO.read(new File(BG_IMG_PATH));
        BufferedImage dstImg = resizeImage(width, height, bgImg);
        File out = new File(filePath);
        if (!ImageIO.write(dstImg, IMG_FORMAT, out)) {
            throw new Exception("生成图片失败");
        }
    }

    private static BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

}